<template>
	<el-upload
		class="avatar-uploader"
		ref="uploadRef"
		action="#"
		:http-request="UploadRequestHandler"
		:limit="1"
		:before-upload="beforeAvatarUpload"
		:on-exceed="handleExceed"
		:list-type="'picture'"
		:on-change="handleChange"
		drag
	>
		<template #trigger>
			<el-button type="primary">select file</el-button>
		</template>
		<el-button class="ml-3" type="success" @click="submitHandler"> upload to server </el-button>

		<template #tip>
			<div class="el-upload__tip">jpg/png/jpeg files with a size less than 2MB</div>
		</template>
	</el-upload>
</template>

<script setup>
import instance from '@/utils/http'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
const uploadRef = ref(null)

const imageUrl = ref('')
const form = reactive({
	file: null,
	filename: null
})

/**
 * 上传类型 / 大小 / 个数
 * @param {*} rawFile
 */
const beforeAvatarUpload = (rawFile) => {
	const typeArr = ['image/jpeg', 'image/jpg', 'image/png'] // 类型
	const uploadSize = rawFile.size / 1024 / 1024 > 2 // 大小
	if (!typeArr.includes(rawFile.type)) {
		ElMessage.error('Avatar picture must be JPG format!')
		return false
	} else if (uploadSize) {
		ElMessage.error('Avatar picture size can not exceed 2MB!')
		return false
	}
	return true
}
/**
 * 文件超出个数限制时的钩子
 */
const handleExceed = () => {
	ElMessage.error('超出最大上传限制')
}

const fileListData = ref([])
/** 覆盖默认行为*/
const UploadRequestHandler = async (params) => {
	// const blob = new Blob([params.file])
	// file 是blob的子类，直接 用 file 即可
	const buffer = await blobToArrayBuffer(params.file)
	console.log('%c [  ]-69', 'font-size:13px; background:pink; color:#bf2c9f;', buffer)
	const objectUrl = blobToObjectUrl(params.file) // 这里可以通过 URL.createObjectURL 设置缩略图，当然可以list-type 来做图片list 展示

	console.log('%c [ objectUrl ]-69', 'font-size:13px; background:pink; color:#bf2c9f;', objectUrl)
	form.file = params.file
	form.filename = params.file.name
}
const submitHandler = async () => {
	if (!form.file) return // empty block submit
	let formData = new FormData()
	formData.append('file', form.file)
	formData.append('filename', form.filename)
	try {
		const { code, codeText, servicePath } = await instance.post('/upload_single', formData)
		if (+code === 0) {
			ElMessage.success(`文件已经上传成功~~,您可以基于 ${servicePath} 访问这个资源~~`)
			return
		}
		return Promise.reject(codeText)
	} catch (error) {
		ElMessage.error(error)
	} finally {
		uploadRef.value.clearFiles()
	}
}

const handleChange = (file, fileList) => {
	fileListData.value = fileList
}
</script>

<style scoped lang="scss">
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
